package WIAB::Controller::SiteMap;

use strict;
use warnings;
use base 'Catalyst::Controller';

use WWW::Google::SiteMap;
use File::Finder;

=head1 NAME

WIAB::Controller::SiteMap - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller to generate google sitemap and html sitemap.

TODO: May want to consider making sub google requre authorisation by
user or ip address so that the sitemap can't be abused (ping flood).
However leaving it for now as it would introduce more complexity.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;
    $c->detach('google');
    return 0;
}

sub google : Local {
    my ($self, $c) = @_;
    my $base = Path::Class::Dir->new($c->config->{content});
    my $sitemap_file = Path::Class::Dir->new($c->config->{sitemap_loc})->file('sitemap.gz');
    my $start_dir = $base;
    my $prune_svn = File::Finder->type('d')->name('.svn')->prune;
    my @dirs = $prune_svn->or->type('d')->in("$start_dir");
    foreach (@dirs) {
        $_ = _get_relative_dir("$start_dir", $_);
    }
    my $map = WWW::Google::SiteMap->new(
        file => "$sitemap_file",
        pretty => 1,
    );
    my $loc = $c->uri_for('/content');
    $map->add(loc => $loc->as_string);
    foreach (@dirs) {
        $loc = $c->uri_for("/content/$_");
        $map->add(loc => $loc->as_string);
    }
    $loc = $c->uri_for('/content/rss');
    $map->add(loc => $loc->as_string);

    $map->write;

    if ($c->config->{gsm_ping} == 1) {
        use WWW::Google::SiteMap::Ping;
        my $sitemap_url = $c->uri_for('/static/sitemap.gz');
         my $ping = WWW::Google::SiteMap::Ping->new(
           "$sitemap_url"
         );
        $ping->submit;
        if ($ping->success) {
            $c->res->body('sitemap generated and google ping succeeded');
            $c->detach();
        }
        else {
            $c->res->body('sitemap generated and google ping failed');
            $c->detach();
        }
    }
    $c->res->body("google sitemap generated, set config var 'gsm_ping' to equal 1 to enable automatic ping of google on generation");
    $c->detach();
}

=head2 _get_relative_dir ($base_dir, $cwd)

Returns the relative portion of $cwd relative to $base_dir for uri
generation for the google sitemap.

=cut

sub _get_relative_dir {
    my ($base, $dir) = @_;
    $dir =~ /$base(.*)/;
    return $1;
}

    
sub html : Local {
    my ($self, $c) = @_;
    # generate an html sitemap (nested lists?) here;
    $c->stash->{template} = 'sitemap.tt';
}
=head1 AUTHOR

Kieren Diment

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
